<template>
  <div class="flow-group" v-loading="groupLoading">
    <div class="content-top">
      <div class="header-left">流程组</div>
      <div class="top-right">
        <el-button v-if="hasPermission(['flow:manage:list:addGroup'])" type="primary" @click="handleAddGroup">新建分组</el-button>
      </div>
    </div>
    <div class="content-box ruifox-content-box">
      <SearchCmp v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="queryData" @onSubmit="handleSearch" />
      <el-row class="content-wrap">
        <el-col :span="5" class="content-left">
          <div class="content-left-header">流程分组</div>
          <div class="content-left-body">
            <el-scrollbar height="550px">
              <el-tree v-loading="groupLoading" :data="groupList" :props="groupProps" node-key="id" :expand-on-click-node="false" @node-click="handleChangeGroup" :indent="0" class="group-tree">
                <template #default="{ node, data }">
                  <div class="group-tree-node">
                    <div class="tree-node-label" :style="{ paddingLeft: (node.level - 1) * 10 + 'px' }" :title="node.label">
                      <i class="iconfont">&#xe6a7;</i>
                      {{ node.label }}
                    </div>
                    <div class="tree-options">
                      <el-dropdown>
                        <i class="iconfont">&#xe78d;</i>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item v-if="hasPermission(['flow:manage:list:editGroup'])"><el-button type="primary" link @click="handleEditGroup(data)">编辑</el-button></el-dropdown-item>
                            <el-dropdown-item v-if="hasPermission(['flow:manage:list:deleteGroup'])"><el-button type="danger" link @click="handleDeleteGroup(data)">删除</el-button></el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </div>
                </template>
              </el-tree>
            </el-scrollbar>
          </div>
        </el-col>
        <el-col :span="19" class="content-right">
          <div class="content-right-header">
            <div class="header-left">
              <span class="group-name">{{ curGroup ? curGroup.name : '未选择分组，默认展示所有审核流' }}</span>
              <span class="total">{{ `（数量：${flowList?.length || 0}）` }}</span>
              <el-button v-if="curGroup" type="primary" link @click="handleShowAll">查看全部</el-button>
            </div>
            <div class="header-right">
              <el-button v-if="hasPermission(['flow:manage:setting:add'])" type="primary" size="small" @click="handleAddFlow">添加审核流</el-button>
            </div>
          </div>
          <div class="content-right-body">
            <RuifoxTable class="my-table" :loading="tableLoading" :default-index="true" :default-checkbox="false" v-model:tableData="flowList" v-model:fieldList="fieldList" :tableHeight="550">
              <template #groupId="{ element }">
                <p>{{ groupMapping[element.groupId] }}</p>
              </template>
              <template #options="{ element }">
                <div class="table-td-option">
                  <el-button type="primary" link @click="handleFlowDetail(element)">详情</el-button>
                  <el-button type="primary" link @click="handleFlowPicture(element)">流程图</el-button>
                  <el-dropdown class="more-icon-box">
                    <i class="iconfont more-icon" style="cursor: pointer;">&#xe78d;</i>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item v-if="hasPermission(['flow:manage:list:deleteFlow'])" @click="handleDeleteFlow(element)">删除</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </template>
            </RuifoxTable>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 流程分组添加 -->
    <el-dialog v-model="groupDialog" :title="groupForm.id ? '编辑分组' : '添加分组'" width="500px" @close="resetGroupForm">
      <el-form ref="groupFormRef" :rules="groupFormRules" :model="groupForm" label-width="auto"> 
        <el-form-item label="分组名称" prop="name">
          <el-input v-model="groupForm.name" placeholder="请输入分组名称" />
        </el-form-item>
        <el-form-item label="删除api" prop="deleteApi">
          <el-input v-model="groupForm.deleteApi" placeholder="请输入删除api" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleSubmitGroup">确认</el-button>
          <el-button @click="groupDialog = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 流程图预览 -->
    <el-dialog v-model="pictureDialog" title="流程图" width="1200px">
      <div style="height: 600px;overflow: auto;">
        <NodeSetting :nodeConfig="pictureConfig" :showZoom="false" style="pointer-events: none;" />
      </div>
    </el-dialog>
    <!-- 流程详情预览 -->
    <el-dialog v-model="detailDialog" title="流程详情" width="500px">
      <el-timeline>
        <NodeRender :nodeConfig="nodeConfig" />
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script setup>
/* eslint-disable */
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { deleteFlowList, getFlowList, deleteFlow, getFlowGroupList, insertGroup, deleteGroup, updateGroup } from '@/api/workflow'
import { createMapping } from '@/utils/tools'
import { request, hasPermission } from '@ruifox-cms/utils'
import { useStore } from 'vuex'

const store = useStore()
const router = useRouter()
/********************************左侧流程组*************************/
// 流程组列表
const groupProps = {
  children: 'children',
  label: 'name'
}
const groupList = ref([])
const groupMapping = ref({})
const deleteApiMapping = ref({})
const groupOptions = ref([])
const groupLoading = ref(false)
const _getGroupList = async () => {
  groupLoading.value = true
  const res = await getFlowGroupList()
  if(res.code === 20000){
    groupList.value = res.data
    groupMapping.value = createMapping(res.data, {keyProp: 'id', valueProp: 'name'})
    deleteApiMapping.value = createMapping(res.data, {keyProp: 'id', valueProp: 'deleteApi'})
    groupOptions.value = res.data.map(item => ({ label: item.name, value: item.id }))
  }
  groupLoading.value = false
}
_getGroupList()

// 切换组别
const curGroup = ref(null)
const handleChangeGroup = (data) => {
  if(curGroup.value?.id === data.id) return
  curGroup.value = data
  queryData.groupId = data.id
  _getFlowList()
}

// 添加流程组
const groupDialog = ref(false)
const groupFormRef = ref(null)
const groupFormRules = reactive({
  name: [{ required: true, message: '请输入分组名称', trigger: 'blur' }],
  deleteApi: [{ required: true, message: '请输入删除api', trigger: 'blur' }]
})
const defaultGroupForm = reactive({
  id: '',
  name: '',
  deleteApi: ''
})
const groupForm = reactive(Object.assign({}, defaultGroupForm))
const handleAddGroup = () => {
  groupDialog.value = true
}

// 编辑流程组
const handleEditGroup = (data) => {
  console.log(data, 22222)
  Object.assign(groupForm, data)
  groupDialog.value = true
}

// 提交流程分组
const handleSubmitGroup = async () => {
  groupFormRef.value.validate(async valid => {
    console.log(valid, 78787878)
    if(!valid) return
    let res
    if(groupForm.id){
      res = await updateGroup(groupForm)
    }else{
      res = await insertGroup(groupForm)
    }
    if(res.code === 20000){
      const msg = groupForm.id? '编辑成功' : '添加成功'
      ElMessage.success(msg)
      _getGroupList()
      if(curGroup.value?.id === groupForm.id) {
        Object.assign(curGroup.value, groupForm)
      }
      groupDialog.value = false
    }
  })
}

// 删除流程组
const handleDeleteGroup = async (data) => {
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否删除所选功能？</p><span style="font-size: 14px;color: #FF5240;">删除后功能将被移除</span></div>', '删除确认', {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    }).then(async () => {
      const res = await deleteGroup({ id: data.id })
      if(res.code === 20000){
        ElMessage.success('删除成功')
        if(curGroup.value?.id === data.id) {
          curGroup.value = null
          flowList.value = []
        }
        _getGroupList()
      }
    }).catch(() => {
      ElMessage.info('已取消删除')
    })
}

const resetGroupForm = () => {
  groupFormRef.value.resetFields()
  Object.assign(groupForm, defaultGroupForm)
}
/*******************************右侧流程列表************************/
//获取流程列表
const searchCmpArray = ref([
  { label: '审核流名称', key: 'name' }, 
  {label: '所在分组', key: 'groupId', form_type: 'select', options: groupOptions.value}
])
const fieldList = ref([
  {
    title: '名称',
    name: 'name',
    showTextTip: true
  },
  {
    title: '所属分组',
    name: 'groupId',
  },
  {
    title: '流程说明',
    name: 'description',
    showTipText: true,
    minWidth: 300
  },
  {
    title: '进行实例（条）',
    name: 'runningInstanceCount'
  },
  {
    title: '操作',
    width: 180,
    fixed: 'right',
    name: 'options'
  }
])
const tableLoading = ref(false)
const defaultQueryData = reactive({
  groupId: null,
  name: ''
})
const queryData = reactive(Object.assign({}, defaultQueryData))
const flowList = ref([])
const _getFlowList = async () => {
  tableLoading.value = true
  const res = await getFlowList(queryData)
  if(res.code === 20000){
    flowList.value = res.data
  }
  tableLoading.value = false
}
_getFlowList()

// 搜索
const handleSearch = () => {
  _getFlowList()
}

// 查看全部
const handleShowAll = () => {
  queryData.groupId = null
  curGroup.value = null
  _getFlowList()
}

// 创建审核流
const handleAddFlow = () => {
  let toUrl = router.resolve({
    path: '/flow/manage/setting',
    query: {
      groupId: curGroup.value? curGroup.value.id : null
    }
  })
  window.open(toUrl.href, '_blank')
}

// 删除审核流
const handleDeleteFlow = (data) => {
  ElMessageBox.confirm(
    '<div><p style="font-size: 16px;margin-bottom: 15px;">是否删除该审核流？</p><span style="font-size: 14px;color: #FF5240;">删除后审核流将被移除</span></div>',
    '删除确认',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
    }
  ).then(async () => {
    const apiPath = deleteApiMapping.value[data.groupId]
    if(!apiPath) {
      ElMessage.error('删除api未配置')
      return
    }
    const res = await request({
      url: process.env.VUE_APP_BASE_API + apiPath,
      method: 'post',
      data: {
        processDefinitionId: data.processDefinitionId
      }
    })
    if(res.code === 20000){
      ElMessage.success('删除成功')
      _getFlowList()
    }
  }).catch(() => {
    ElMessage.info('取消失败')
  })
}

// 详情
const detailDialog = ref(false)
const nodeConfig = ref(null)
const handleFlowDetail = (data) => {
  nodeConfig.value = JSON.parse(data.json).nodeConfig
  detailDialog.value = true
}

// 流程图
const pictureDialog = ref(false)
const pictureConfig = ref(null)
const handleFlowPicture = (data) => {
  pictureConfig.value = JSON.parse(data.json).nodeConfig
  pictureDialog.value = true
}
onMounted(() => {
  window['updateFlow'] = val => {
    ElMessage({
      showClose: true,
      message: val,
      type: 'success'
    })
    _getFlowList()
  }
})
onBeforeUnmount(() => {
  window['updateFlow'] = null
})
</script>

<style lang="scss" scoped>
.content-top {
  padding: 10px 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  .header-left {
    font-size: 18px;
    font-weight: 600;
  }
}
.content-box {
  margin-top: 10px;
  .content-wrap {
    margin-top: 10px;
    border: 1px solid #e4e4e4;
    .content-left {
      overflow-x: hidden;
      .content-left-header {
        height: 50px;
        background-color: $backBase;
        width: 100%;
        box-sizing: border-box;
        border-bottom: 1px solid $borderColor;
        padding-left: 46px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
      }
      .content-left-body {
        .group-tree {
          ::v-deep .el-tree-node .el-tree-node__content {
            border-bottom: 1px solid $borderColor;
            height: 48px;
          }
          ::v-deep .el-tree-node__label {
            width: calc(100% - 40px);
            .group-tree-node {
              display: flex;
              justify-content: space-between;
              align-items: center;
              div {
                box-sizing: border-box;
              }
              .tree-node-label,
              .tree-node-icon {
                width: 90%;
                text-overflow: ellipsis;
                overflow: hidden;
                white-space: nowrap;
              }
              .tree-node-path {
                width: 350px;
                flex-grow: 0;
              }
              .tree-node-type {
                width: 380px;
                flex-grow: 0;
              }
              .tree-options {
                display: flex;
                div.button-box {
                  flex-grow: 0;
                  position: relative;
                  i {
                    position: absolute;
                    right: 0;
                    top: 8px;
                    color: $mainColor;
                  }
                }
              }
            }
          }
        }
      }
    }
    .content-right {
      border-left: 1px solid #e4e4e4;
      .content-right-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 13px;
        height: 50px;
        background: #dfe9f5;
        .header-left {
          display: flex;
          align-items: center;
          line-height: 14px;
          font-size: 14px;
          .group-name {
            color: #666;
          }
          .total {
            color: $mainColor;
          }
        }
      }
      .content-right-body{
        width: 100%;
        ::v-deep(.my-table){
          .el-table__cell{
            height: 50px;
            padding: 4px 0;
          }
          .el-table__header{
            width: 100% !important;
          }
          .el-scrollbar__view{
            width: 100% !important;
          }
          .el-table__body{
            width: 100% !important;
          }
          .my-table-index{
            width: 40px !important;
          }
          .cell{
            height: 100%;
            display: flex;
            align-items: center;
          }
          .dropdown-botton{
            padding: 10px;
            display: flex;
            flex-direction: column;
          }
          .el-table-column--selection{
            width: 40px;
          }
          .el-badge__content{
            transform: scale(0.7);
            right: -15px;
            top: -8px;
          }
        }
      }
    }
  }
}
</style>